/* Copyright by GD GameDuell GmbH, All Rights Reserved
 * This document is strictly confidential and sole property of GD GameDuell GmbH, Berlin, Germany
 */

package de.gameduell.loader.src {
	import de.gameduell.framework.asset.AssetEvent;
	import de.gameduell.framework.asset.AssetGroup;
	import de.gameduell.framework.asset.IAsset;
	import de.gameduell.framework.locale.LocaleData;
	import de.gameduell.framework.util.FlashVars;

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * Class LoaderBar
	 * Holds a sprite for showing the progress of the current loading task.
	 * Basically the bar animation is a movieclip with a length of 100 frames.
	 * Every frame represents a progress of 1%.
	 */
	public class LoaderBar extends MovieClip implements ILoaderBar {
		protected var asset:IAsset;
		protected var loaderClip:MovieClip;
		protected var _timeline:MovieClip;
		protected var _loaderBar:MovieClip;
		protected var localeData:LocaleData;

		/**
		 * Class constructor
		 * @param aLoaderClip	a sprite which should showing the progress
		 * @param aAssets		a list of assets to calculate the current progress
		 */
		public function LoaderBar() {
			localeData = LocaleData.getInstance();
			FlashVars.setKeyValue("purl", "http://www.gameduell.com");
			localeData.setValue("msgOfTheDay", "motd_" + int(Math.random()*15));
		}

		/**
		 * Handler for the progress event - scales the loaderBar sprite.
		 * Every time the loader made progress this function will be called.
		 */
		protected function progress(event:AssetEvent):void {
			_loaderBar.gotoAndStop(Math.round(event.asset.percentLoaded));
		}
		
		public function init(assetGroup:AssetGroup, aContent:MovieClip):void {
			asset = assetGroup;
			_timeline = aContent;
			var background:Sprite = _timeline.getChildByName("background") as Sprite;
			_loaderBar = _timeline.getChildByName("loaderBar") as MovieClip;
	
			background.width = _timeline.stage.stageWidth;
			background.height = _timeline.stage.stageHeight;

			_loaderBar.x = (_timeline.stage.stageWidth / 2) - (_loaderBar.width / 2);
			
			assetGroup.addEventListener(AssetEvent.COMPLETE, complete);
			assetGroup.addEventListener(AssetEvent.PROGRESS, progress);
			assetGroup.load();
		}
		
		protected function complete(event:AssetEvent):void {
			dispatchEvent(new Event(AssetEvent.COMPLETE));
		}
	}
}